package com.yunwaikeji.gy_tool_library.widget;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.yunwaikeji.gy_tool_library.R;

/**
 * 等待对话框
 */
public class GYLoadingDialog extends Dialog {
    private TextView tipTextView;
    private AnimationDrawable animationDrawable;
    private ImageView loadImg;
    private String tipText;
    private final String normalString = "请稍后";
    private String nowString;
    private long changeTime = 1000;
    private int pointCount = 3;

    public GYLoadingDialog(Context context) {
        super(context, R.style.dialog);
        initView();
    }

    public GYLoadingDialog(Context context, int themeResId) {
        super(context, themeResId);
        initView();
    }

    private void initView() {
        setContentView(R.layout.dialog_gy_loading);
        setCancelable(true);
        setCanceledOnTouchOutside(false);
        nowString = normalString;

        tipTextView = findViewById(R.id.tipText);
        tipTextView.setText(tipText);
        loadImg = findViewById(R.id.loadImg);

        animationDrawable = (AnimationDrawable) loadImg.getDrawable();
        animationDrawable.start();

        setShowTip(true);
    }

    public GYLoadingDialog setTipText(String text) {
        tipText = text;
        return this;
    }

    public GYLoadingDialog setShowTip(boolean showTip) {
        if (showTip) {
            handler.post(runnable);
        } else {
            handler.removeCallbacks(runnable);
            tipTextView.setText("");
        }
        return this;
    }

    private final Handler handler = new Handler();
    private final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (TextUtils.isEmpty(tipText)) {
                tipTextView.setText(nowString);
                nowString += ".";
                if (nowString.length() > normalString.length() + pointCount) {
                    nowString = normalString;
                }
            } else {
                tipTextView.setText(tipText);
            }
            handler.postDelayed(runnable, changeTime);
        }
    };
}
